<template>
  <div class="app-container">
    <div class="form-container">
      <el-row
        class="form-container-head"
        align="middle"
        justify="space-between"
      >
        <!-- 左侧按钮组 -->
        <el-col
          :xs="24"
          :sm="16"
          :md="12"
          :lg="8"
          class="button-group"
        >
          <el-button
            class="ml-20 create-form"
            size="large"
            type="primary"
            @click="handleOpenCreateForm"
            v-hasPermi="['form:my:create']"
          >
            ＋ {{ $t("form.formLayout.newProject") }}
          </el-button>
          <el-button
            v-if="isOpenAi"
            v-hasPermi="['form:my:create']"
            class="ml-20 ai-create-form"
            size="large"
            @click="handleOpenAIForm"
          >
            <el-icon
              class="mr-5"
              size="20"
            >
              <TablerBrandAirbnb />
            </el-icon>
            {{ $t("form.formLayout.aiCreateForm") }}
          </el-button>
          <el-button
            class="ml-20 create-folder"
            size="large"
            @click="handleOpenCreateFolder"
          >
            {{ $t("client.my.newFolder") }}
          </el-button>
        </el-col>

        <!-- 右侧工具栏 -->
        <el-col
          :xs="24"
          :sm="8"
          class="right-toolbar"
        >
          <div class="container-head-search">
            <el-icon @click="queryProjectPage">
              <ele-Search />
            </el-icon>
            <el-form @submit.prevent>
              <el-input
                @keyup.enter="queryProjectPage"
                v-model="queryParams.name"
                size="default"
                :placeholder="$t('client.my.search')"
              />
            </el-form>
          </div>
          <div>
            <span
              class="switch-style-btn"
              :type="dataShowType === 'card' ? 'primary' : 'default'"
              @click="toggleDataShowType"
            >
              <el-icon
                size="20"
                v-if="dataShowType === 'card'"
              >
                <i class="iconfont icon-caidanguanli" />
              </el-icon>
              <el-icon
                v-else
                size="18"
              >
                <ele-Menu />
              </el-icon>
            </span>
          </div>
        </el-col>
      </el-row>

      <div class="form-breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="getFolderForm(0)">{{ $t("client.my.myForm") }}</el-breadcrumb-item>
          <el-breadcrumb-item
            v-for="b in breadcrumbList"
            :key="b.id"
          >
            {{ b.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <Transition
        name="slide-fade"
        mode="out-in"
      >
        <form-card-list
          v-if="dataShowType === 'card'"
          v-loading="projectListLoading"
          v-model:project-list="projectList"
          @enter-folder="handleEnterFolder"
          @move="handleOpenMoveFolderDialog"
          @refresh="queryProjectPage"
          @rename-folder="handleRenameFolderDialog"
          @sort-top="handleSortTop"
        />
        <my-form-table
          v-else-if="dataShowType === 'table'"
          v-loading="projectListLoading"
          v-model:project-list="projectList"
          @enter-folder="handleEnterFolder"
          @move="handleOpenMoveFolderDialog"
          @refresh="queryProjectPage"
          @rename-folder="handleRenameFolderDialog"
          @sort-top="handleSortTop"
        />
      </Transition>
      <div class="project-page-view">
        <el-pagination
          v-if="total > 10"
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :total="total"
          background
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="createFolderVisible"
      :title="$t('client.my.newFolder')"
      width="30%"
    >
      <el-form
        ref="createFolderRef"
        :model="folderData"
        label-width="100px"
      >
        <el-form-item
          :label="$t('client.my.folderName')"
          :rules="[{ required: true, message: $t('client.my.folderNameRequired') }]"
          prop="name"
        >
          <el-input
            v-model="folderData.name"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createFolderVisible = false">{{ $t("client.my.cancel") }}</el-button>
          <el-button
            type="primary"
            :loading="requestLoading.pushFolderData"
            @click="createFormFolderHandle"
          >
            {{ $t("client.my.yes") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="folderTreeVisible"
      :title="$t('client.my.moveFolder')"
      width="30%"
    >
      <el-tree
        ref="folderTree"
        :data="folderTreeData"
        :props="folderTreeProps"
        check-strictly
        highlight-current
        node-key="id"
        show-checkbox
        default-expand-all
        @check-change="handleFolderTreeChange"
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <i class="iconfont icon-wenjianjia" />
            <span class="mp5">{{ node.label }}</span>
          </span>
        </template>
      </el-tree>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="folderTreeVisible = false">{{ $t("client.my.cancel") }}</el-button>
          <el-button
            type="primary"
            @click="handleMoveFolder"
          >
            {{ $t("client.my.yes") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    <CreateForm
      ref="createFormRef"
      :folder-id="currentFormFolder?.id"
    />
    <el-dialog
      v-model="renameFolderVisible"
      :title="$t('client.my.renameFolder')"
      width="30%"
    >
      <el-form
        ref="renameFolder"
        :model="folderData"
        label-width="100px"
      >
        <el-form-item
          :label="$t('client.my.folderName')"
          :rules="[{ required: true, message: $t('client.my.folderNameRequired') }]"
          prop="name"
        >
          <el-input
            v-model="folderData.name"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameFolderVisible = false">{{ $t("client.my.cancel") }}</el-button>
          <el-button
            type="primary"
            @click="handleRenameFolder"
          >
            {{ $t("client.my.yes") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    <ChatFormDialog ref="chatFormRef" />
  </div>
</template>
<script setup name="MyProject">
import { onMounted, reactive, ref } from "vue";
import { MessageUtil } from "@/utils/messageUtil";
import {
  createFormRequest,
  getUserFormFolderTreeRequest,
  pageFormRequest,
  sortTopFormRequest,
  updateFormRequest
} from "@/api/project/form";
import FormCardList from "./card.vue";
import MyFormTable from "./table.vue";
import _cloneDeep from "lodash-es/cloneDeep";
import { useFormInfo } from "@/stores/formInfo";
import { i18n } from "@/i18n";
import { storeToRefs } from "pinia";
import CreateForm from "@/views/project/my/CreateForm.vue";
import ChatFormDialog from "@/views/ai/form/ChatFormDialog.vue";
import TablerBrandAirbnb from "~icons/tabler/brand-airbnb";

import { aiChatIsOpenRequest } from "@/api/project/ai";
const createFolderVisible = ref(false);
const folderTreeVisible = ref(false);
const renameFolderVisible = ref(false);
const dataShowType = ref("card");
const total = ref(0);
const queryParams = reactive({
  current: 1,
  size: 12,
  name: "",
  createUserName: "",
  beginDateTime: null,
  endDateTime: null,
  status: null,
  folderId: 0
});

let folderData = ref({
  name: i18n.global.t("client.my.folderName"),
  type: 3,
  folder: true,
  formKey: "",
  folderId: 0
});
const breadcrumbList = ref([]);
const projectList = ref([]);
const projectListLoading = ref(false);
const folderTreeData = ref([]);
const folderTreeProps = ref({
  children: "children",
  label: "name"
});
const requestLoading = reactive({
  pushFolderData: false
});
const folderTree = ref(null);

const formInfoStore = useFormInfo();

const { currentFormFolder, currentPage } = storeToRefs(formInfoStore);

const createFolderRef = ref(null);

const createFormFolderHandle = () => {
  createFolderRef.value.validate(valid => {
    if (valid) {
      folderData.value.type = 3;
      folderData.value.folder = true;
      requestLoading.pushFolderData = true;
      createFormRequest(folderData.value)
        .then(() => {
          requestLoading.pushFolderData = false;
          MessageUtil.success(i18n.global.t("formI18n.all.success"));
          queryProjectPage();
          createFolderVisible.value = null;
        })
        .catch(() => {
          requestLoading.pushFolderData = false;
          MessageUtil.success(i18n.global.t("formI18n.all.fail"));
        });
    } else {
      return false;
    }
  });
};
const toggleDataShowType = () => {
  dataShowType.value = dataShowType.value === "card" ? "table" : "card";
};

const handlePageChange = () => {
  console.log("handlePageChange", queryParams.current);
  currentPage.value = queryParams.current;
  queryProjectPage();
};

const queryProjectPage = () => {
  projectListLoading.value = true;
  pageFormRequest(queryParams).then(res => {
    const { records, size } = res.data;
    projectList.value = records;
    total.value = res.data.total;
    projectListLoading.value = false;
  });
};

const handleOpenMoveFolderDialog = item => {
  folderTreeVisible.value = true;
  folderData.value = item;
  getUserFormFolderTreeRequest().then(res => {
    folderTreeData.value = [{ id: 0, name: i18n.global.t("client.my.rootDirectory"), children: res.data }];
  });
};

const handleRenameFolderDialog = item => {
  renameFolderVisible.value = true;
  folderData.value = _cloneDeep(item);
};

const handleSortTop = (item, isTop) => {
  item.sort = isTop ? 1 : null;
  sortTopFormRequest(item).then(() => {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
    queryProjectPage();
  });
};

const handleFolderTreeChange = (data, checked, node) => {
  if (checked) {
    folderTree.value.setCheckedNodes([data]);
  }
};
const handleMoveFolder = () => {
  if (!folderTree.value.getCheckedKeys().length > 0) {
    MessageUtil.warning(i18n.global.t("client.my.chooseFolder"));
    return;
  }
  const folderId = folderTree.value.getCheckedKeys()[0];
  folderData.value.folderId = folderId;
  updateFormRequest(folderData.value).then(res => {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
    folderTreeVisible.value = false;
    queryProjectPage();
  });
};
const handleRenameFolder = () => {
  updateFormRequest(folderData.value).then(res => {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
    renameFolderVisible.value = null;
    folderData.value = {};
    queryProjectPage();
  });
};

const handleEnterFolder = (f, isEnter = true) => {
  if (f.id === queryParams.folderId) {
    return;
  }
  if (isEnter) {
    // 清空分页 不然把外面的当前页带到里面了
    currentPage.value = 1;
  }
  getFolderForm(f.id);
  breadcrumbList.value.push(f);
  formInfoStore.setCurrentFormFolder(f);
};

const getFolderForm = id => {
  queryParams.folderId = id;
  if (id === 0) {
    // 回到根目录
    formInfoStore.setCurrentFormFolder({
      id: 0
    });
    breadcrumbList.value = [];
    currentPage.value = 1;
    queryParams.current = 1;
  } else {
    queryParams.current = currentPage.value ? currentPage.value : 1;
  }

  queryProjectPage();
};

const isOpenAi = ref(false);

onMounted(() => {
  let f = currentFormFolder.value;
  if (f.id) {
    handleEnterFolder(f, false);
  } else {
    queryParams.current = currentPage.value;
    queryProjectPage();
  }
  // 查询接口是否配置了ai
  aiChatIsOpenRequest().then(res => {
    isOpenAi.value = res.data;
  });
});
const createFormRef = ref(null);

const handleOpenCreateForm = async () => {
  await createFormRef.value?.showForm();
};

const handleOpenCreateFolder = () => {
  folderData.value = {
    name: i18n.global.t("client.my.folderName"),
    type: 3,
    folder: true,
    formKey: "",
    folderId: 0
  };
  createFolderVisible.value = true;
};

const chatFormRef = ref(null);

const handleOpenAIForm = async () => {
  await chatFormRef.value?.open();
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #ffffff;
  border-radius: 10px;
}

.form-container {
  margin: 0 auto;
  user-select: none;
  -webkit-user-select: none;
}

.project-page-view {
  margin-top: 30px;
  text-align: center;
}

.container-head-search {
  border: 1px solid #898989;
  border-radius: 6px;
  width: 163px;
  height: 29px;
  display: flex;
  align-items: center;
  color: var(--el-text-color-secondary);

  :deep(.el-icon) {
    cursor: pointer;
    font-size: 18px;
    width: 24px;
    margin-left: 8px;
  }

  :deep(.el-input__wrapper) {
    background-color: transparent;
    box-shadow: none;
  }
}

.container-head-search {
  border: 1px solid transparent;
  border-radius: 8px;
  width: 193px;
  height: 29px;
  display: flex;
  align-items: center;
  color: #4c4edb;
  transition: all 0.3s; /* 对所有属性添加过渡效果 */
}

.container-head-search:hover {
  border: 1px solid #4c4edb;
  width: 263px;
  color: #4c4edb;
}

.container-head-search .el-icon {
  cursor: pointer;
  font-size: 18px;
  width: 24px;
  margin-left: 8px;
}

.container-head-search .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

.form-create {
  width: 209px;
  height: 38.32px;
  margin-left: 20px;
  display: flex;
  align-items: center;
  justify-content: space-around;

  .form-create-folder {
    background-color: transparent;
    border: none;
  }

  .form-sort {
    background: transparent;
    border: none;
    color: #6a6a6a;
  }
}

.add-folder-button:hover {
  width: 209px;
  height: 38.32px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  color: #4c4edb;
}

.switch-style-btn {
  margin-left: 20px;

  &:hover {
    color: #4c4edb;
    transform: scale(1.2);
  }

  color: var(--el-text-color);
}

.change-button:hover {
  .form-sort {
    color: #4c4edb;
  }
}

.form-breadcrumb {
  margin: 20px 50px 10px 0;
}

.right-toolbar {
  display: flex;
  align-items: center;
  align-content: flex-end;
  justify-content: flex-end;
  padding-right: 27px;
}

:deep(.el-breadcrumb__inner) {
  cursor: pointer !important;
  font-weight: 700 !important;
  font-size: 16px;
}
@media screen and (max-width: 700px) {
  .right-toolbar {
    display: flex;
    align-items: center;
    align-content: flex-end;
    justify-content: flex-end;
    padding-right: 27px;
    margin-top: 20px;
    width: 100%;
  }

  .switch-style-btn {
    margin-left: 20px;

    color: var(--el-text-color);
  }
  .container-head-search {
    border: 1px solid #4c4edb;
    border-radius: 6px;
    width: 100%;
    height: 29px;
    display: flex;
    align-items: center;
  }

  .create-form {
    width: 50%;
  }
}

.ai-create-form {
  background: linear-gradient(60deg, #7879ff 0%, #3a3cb8 100%);
  border: none;
  color: white;

  &:hover {
  background: linear-gradient(90deg, #7879ff 0%, #3a3cb8 100%);
  }
}
</style>
